import Vue from 'vue'
import ReconnectingWebSocket from 'reconnecting-websocket'
import store from '../store/index'
import router from '../router'

Vue.use(router)

let Socket = {
  Socket: null,
  sendData (controller = '', params = {}) {
    return new Promise((resolve, reject) => {
      let data = {
        'action': controller,
        'params': params
      }
      Socket.Socket.send(JSON.stringify(data))
      Socket.Socket.addEventListener('message', (res) => {
        if (res.data === 'pong') {
          resolve()
          return
        }
        res = JSON.parse(res.data)
        if (res.msg === 'ok') {
          resolve(res)
        } else {
          resolve(res)
        }
      })
    })
  },
  setStoreList (method = 'setList', data) {
    store.commit(method, data)
  },
  pingInterval: null
}

export const urlProvider = (userAuth) => {
  if (!userAuth) {
    return Socket.close()
  }
  let userInfo = userAuth
  return `wss://game.dz8888.com/imchat/?token=${userInfo.token}&uid=${userInfo.userId}&terminal=2`
}

export const initSocket = () => {
  Socket.Socket = new ReconnectingWebSocket(urlProvider(JSON.parse(localStorage.getItem('userAuth'))))

  Socket.Socket.onopen = () => {
    console.log('服务器连接成功')
    Socket.pingInterval = setInterval(() => {
      Socket.Socket.send('ping')
    }, 50000)
    // Socket.sendData('getImUserInfo').then(res => {
    //   let obj = res.data
    //   obj.OnFAdd = filterOnOff(obj.OnFAdd)
    //   obj.OnFSearch = filterOnOff(obj.OnFSearch)
    //   obj.OnMout = filterOnOff(obj.OnMout)
    //   obj.OnRed = filterOnOff(obj.OnRed)
    // })
  }

  Socket.Socket.onerror = () => {
    console.log('服务器连接失败')
  }

  Socket.Socket.onclose = () => {
    clearInterval(Socket.pingInterval)
  }

  Socket.Socket.addEventListener('message', (res) => {
    if (res.data === 'pong') return
    res = JSON.parse(res.data)

    let action = res.action || ''
    return new Promise((resolve, reject) => {
      switch (action) {
        case 40001: // 获取主页聊天列表
          let sum = 0
          res.data.forEach(item => {
            item.Notice = parseInt(item.Notice)
            sum += item.Notice
          })
          if (sum > 0) {
            Socket.setStoreList('setDetail', Object.assign({ info: true }, { type: 'chatDot' }))
          } else {
            Socket.setStoreList('setDetail', Object.assign({ info: false }, { type: 'chatDot' }))
          }
          Socket.setStoreList('setList', Object.assign({ list: res.data }, { type: 'chatList' }))
          break
        case 10002: // 个人信息
          let obj = res.data
          obj.OnFAdd = filterOnOff(obj.OnFAdd)
          obj.OnFSearch = filterOnOff(obj.OnFSearch)
          obj.OnMout = filterOnOff(obj.OnMout)
          obj.OnRed = filterOnOff(obj.OnRed)
          obj.onGroup = filterOnOff(obj.onGroup)
          Socket.setStoreList('setDetail', Object.assign({ info: obj }, { type: 'userData' }))
          Socket.sendData('ChatDataList')
          break
        case 10008: // 设置性别
          if (res.msg === 'ok') {
            resolve()
          }
          // Socket.setStoreList('sex', Object.assign({ info: res.data }, { type: 'userData' }))
          break
        case 10003: // 搜索联系人
          Socket.setStoreList('setList', Object.assign({ list: res.data }, { type: 'searchBook' }))
          break
        case 10004: // 搜索群
          Socket.setStoreList('setList', Object.assign({ list: res.data }, { type: 'searchGroupBook' }))
          break
        case 20001: // 好友列表
          Socket.setStoreList('setList', Object.assign({ list: res.data }, { type: 'friendList' }))
          break
        case 300001: // 密群列表
          Socket.setStoreList('setList', Object.assign({ list: res.data }, { type: 'groupList' }))
          break
        case 20002: // 好友详情
          Socket.setStoreList('setDetail', Object.assign({ info: res.data }, { type: 'feiendDetail' }))
          break
        case 20003: // 搜索添加好友返回详情
          Socket.setStoreList('setDetail', Object.assign({ info: res.data }, { type: 'feiendDetail' }))
          break
        case 50001: // 有新消息
          if (router.currentRoute.path === '/home') {
            Socket.sendData('ChatDataList')
            Socket.setStoreList('setDetail', Object.assign({ info: true }, { type: 'chatDot' }))
          }
          break
        default:
          resolve()
      }
    })
  })
}

export const filterOnOff = (str = '2') => {
  if (str === '1') {
    return true
  } else if (str === '2') {
    return false
  }
}

export default Socket
